package com.lw.sbdemo2.common.ali;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.lw.sbdemo2.common.utils.DateUtils;
import com.lw.sbdemo2.common.utils.IdUtils;
import com.lw.sbdemo2.common.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Date;

/**
 * 阿里oss上传文件
 */
@Slf4j
public class AliOSSUtil {

    public static String upload(File file) {
        if (file == null) {
            return null;
        }
        AliOSSProperties properties = SpringContextHolder.getBean(AliOSSProperties.class);
        // 创建OSS客户端
        OSSClient ossClient = new OSSClient(properties.getEndPoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        try {
            // 判断文件容器是否存在，不存在则创建
            if (!ossClient.doesBucketExist(properties.getBucketName())) {
                ossClient.createBucket(properties.getBucketName());
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(properties.getBucketName());
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            // 创建文件路径
            String fileUrl = DateUtils.toShortStringFormat(new Date()) + "/" + IdUtils.uuid(false);
            // 上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(properties.getBucketName(), fileUrl, file));
            if (null != result) {
                return properties.getFileHost() + fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } finally {
            // 关闭OSS服务，一定要关闭
            ossClient.shutdown();
        }
        return null;
    }
}
